package com.example.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.example.auth.enums.RoleEnum;
import com.example.auth.mapper.SysMenuMapper;
import com.example.auth.mapper.SysRoleMapper;
import com.example.auth.mapper.SysUserRoleMappingMapper;
import com.example.auth.model.VO.SysMenuVO;
import com.example.auth.model.base.Result;
import com.example.auth.model.domain.SysMenu;
import com.example.auth.model.domain.SysRole;
import com.example.auth.model.domain.SysUserRoleMapping;
import com.example.auth.service.IRoleAndMenuService;
import com.example.auth.utils.ClassUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author xijie.wang
 * @decription:菜单/权限
 * @date 2022-04-11 16:56
 */
@Service
@Slf4j
public class RoleAndMenuServiceImpl implements IRoleAndMenuService {

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private SysMenuMapper menuMapper;

	@Autowired
	private SysUserRoleMappingMapper userRoleMappingMapper;


	@Override
	public List<SysMenu> getMenuOrPermissionList(Integer userId, Integer type) {
		if (userId == null) {
			return null;
		}
		return menuMapper.getMenuOrPermissionList(userId, type);
	}

	@Override
	public List<SysRole> getRoleList(Integer userId) {
		return roleMapper.getRoleList(userId);
	}

	@Override
	public Result<List<SysMenuVO>> getMenuList() {
		List<SysMenu> menus = menuMapper.getMenuListByRoleId(getRoleId());
		return Result.ok(ClassUtil.copyList(menus, SysMenuVO.class));
	}

	@Override
	public Result<List<String>> getPermissionCodeList() {
		List<SysMenu> menus = menuMapper.getPermissionCodeByRoleId(getRoleId());
		List<String> permissionCode = menus.stream().map(SysMenu::getCode).collect(toList());
		return Result.ok(permissionCode);
	}

	@Override
	public int saveUserRole(SysUserRoleMapping mapping) {
		return userRoleMappingMapper.insert(mapping);
	}

	@Override
	public SysUserRoleMapping selectUserRoleMapping(Integer userId) {
		return userRoleMappingMapper.selectByUserId(userId);
	}

	@Override
	public SysUserRoleMapping getUserRoleMappingByUserId(Integer userId) {
		return null;
	}

	@Override
	public int updateUserRole(SysUserRoleMapping mapping) {
		return userRoleMappingMapper.updateById(mapping);
	}


	/**
	 * 获取当前角色id
	 *
	 * @return
	 */
	private int getRoleId() {
		boolean flag = StpUtil.isLogin();
		int roleId = RoleEnum.NO_LOGIN.getType();
		if (flag) {
			//如果是游客
			if (StpUtil.hasRole(RoleEnum.VISITOR.getCode())) {
				roleId = RoleEnum.VISITOR.getType();
			}
			//如果是认证用户
			if (StpUtil.hasRole(RoleEnum.AUTH.getCode())) {
				roleId = RoleEnum.AUTH.getType();
			}
		}
		return roleId;
	}
}
